<template>
  <div>
    <v-header :title="$route.query.type=='edit'? '修改地址' : '添加地址'">
      <v-back></v-back>
    </v-header>
    <van-address-edit
      :area-list="areaList"
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      :address-info='AddressInfo'
      @save="onSave"
    />
  </div>
</template>

<script>
import { areaList } from "@vant/area-data";
import { addressAdd,addressEdit } from "@/request/api.js";
export default {
  data() {
    return {
      areaList,
      AddressInfo:{

      },
      info: {
        uid: "",
        regioncode: "",
        username: "",
        userphone: "",
        location: "",
        useraddress: "",
        status: "",
      },
    };
  },
  created(){
    this.info.uid = JSON.parse(localStorage.getItem("userInfo")).uid;
    if(this.$route.query.type=='edit'){
      this.getEdit('id','id')
      this.getEdit('name','username')
      this.getEdit('tel','userphone')
      this.AddressInfo.province=this.$route.query.location.split(' ')[0]
      this.AddressInfo.city=this.$route.query.location.split(' ')[1]
      this.AddressInfo.county=this.$route.query.location.split(' ')[2]
      this.getEdit('addressDetail','useraddress')
      this.getEdit('areaCode','regioncode');
      this.getEdit('isDefault','status')
    }
  },
  methods: {
    getEdit(l,n){
      this.AddressInfo[l]=this.$route.query[n]
    },
    async onSave(content) {
      this.info.regioncode = content.areaCode;
      this.info.username = content.name;
      this.info.userphone = content.tel;
      this.info.location = content.province+' ' + content.city +' '+ content.county;
      this.info.useraddress = content.addressDetail;
      this.info.status = content.isDefault ? 1 : 0;
      if(this.$route.query.type=='edit'){
        this.info.id=this.$route.query.id
        let res=await addressEdit(this.info)
        this.$Toast.success("修改成功！");
        
      }else{
        let res = await addressAdd(this.info);
        this.$Toast.success("添加成功！");
        
      }
      setTimeout(()=>{
          this.$router.replace("/address")
        },2000)
    }
  },
};
</script>
<style scoped>
</style>